package cn.com.generaldata.os.ws.impl.web;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.BillboardUser;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.service.common.BillboardService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.service.impl.web.UnitServiceForWeb;
import cn.com.generaldata.os.vo.BillboardVO;
import cn.com.generaldata.os.vo.ResultVO;

@Component
@InjectName
public class BillboardAction {

	private static final String PROPERTY_NOTICE_RESULT_SIZE = "notice.result.size";
	private static final String GLOBAL_CONF_PATH = "global_conf.properties";
	private static final int DEFAULT_RESULT_SIZE = 20;

	@Autowired
	@Qualifier("unitServiceForWeb")
	private UnitServiceForWeb unitService;

	@Autowired
	private AreaService areaService;

	@Autowired
	private UserService userService;

	@Autowired
	private BillboardService billboardService;

	public String createBillboard(BillboardVO billboard) {
		// return null;
		List<Unit> users = new ArrayList<Unit>();
		String hql = "from Unit as u where 1=1";
		HashMap map = new HashMap();
		if (billboard.getUserIds() == null || billboard.getUserIds().size() == 0
				|| billboard.getUserIds().get(0) == null) {
			hql += " and u.role.id=4";
			if (billboard.getOpreatorId() != null) {
				User user = userService.queryUserById(billboard.getOpreatorId());
				hql += " and exists (select a.id from Area as a where a.id=u.area.id and a.areaCode is not null and a.parentId=:parentId";
				map.put("parentId", user.getArea().getId());
			}
			users = (List<Unit>) unitService.queryUnitsByhql(hql, map, null).getOperationResult();
		} else {
			String[] userIds = new String[billboard.getUserIds().size()];
			billboard.getUserIds().toArray(userIds);

			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", userIds));
			users = (List<Unit>) unitService.queryUnits(filter, null).getOperationResult();
		}

		return billboardService.createBillboard(toPojo(billboard), users);
	}

	public ResultVO<BillboardVO> queryBillboardsInOcean() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("billboardDate");

		return toVoResult(billboardService.queryBillboards(filter, null));
	}

	@At("/company/billboard/list")
	@Ok("jsp:/static/company/billboard/list")
	public ResultVO<BillboardVO> queryBillboardsInEnterprise(HttpServletRequest request, HttpSession session) {

		//当前用户ID
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");

		// 取默认的结果数
		//		Page page = new Page(1, getDefaultResultSize());
		return toVoResult(billboardService.queryBillboardsAndChangStatus(voUser.getUserUnitId(), null));
	}

	// 自加
	public boolean existUnReadBillboards(String userId) {
		Page page = new Page(1, getDefaultResultSize());
		return billboardService.existUnReadStatus(userId, page);
	}

	private int getDefaultResultSize() {
		ClassPathResource resource = new ClassPathResource(GLOBAL_CONF_PATH);
		int resultSize = DEFAULT_RESULT_SIZE;

		FileInputStream fis = null;
		try {
			fis = new FileInputStream(resource.getFile().getAbsolutePath());

			Properties properties = new Properties();
			properties.load(fis);

			String str = properties.getProperty(PROPERTY_NOTICE_RESULT_SIZE, "");
			if (StringUtils.isNotBlank(str)) {
				return Integer.valueOf(str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (Exception e) {
			}
		}
		return resultSize;
	}

	private cn.com.generaldata.os.pojo.Billboard toPojo(BillboardVO billboard) {
		if (billboard != null) {
			User pOperator = new User();
			pOperator.setId(billboard.getOpreatorId());

			return new cn.com.generaldata.os.pojo.Billboard(billboard.getId(), pOperator,
					billboard.getBillboardTitle(), billboard.getBillboardContent(), billboard.getBillboardDate(), null,
					billboard.getBillboardIndustryId());
		}
		return null;
	}

	private BillboardVO toVo(cn.com.generaldata.os.pojo.Billboard pBillboard) {
		if (pBillboard != null) {
			List<String> userIds = new ArrayList<String>();
			if (pBillboard.getBillboardUsers() != null) {
				for (BillboardUser billboardUser : pBillboard.getBillboardUsers()) {
					userIds.add(billboardUser.getUser().getId());
				}
			}

			String operatorId = pBillboard.getOperator() == null ? null : pBillboard.getOperator().getId();
			return new BillboardVO(pBillboard.getId(), operatorId, pBillboard.getBillboardTitle(),
					pBillboard.getBillboardContent(), pBillboard.getBillboardDate(), userIds,
					pBillboard.getBillboardIndustryId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<BillboardVO> toVoResult(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<BillboardVO> result = new ResultVO<BillboardVO>();

		List<BillboardVO> billboards = new ArrayList<BillboardVO>();
		if (pResult != null) {
			for (cn.com.generaldata.os.pojo.Billboard pBillboard : (List<cn.com.generaldata.os.pojo.Billboard>) pResult
					.getOperationResult()) {
				billboards.add(toVo(pBillboard));
			}
			result.setPageNumber(pResult.getPageNumber());
			result.setPageSize(pResult.getPageSize());
			result.setTotalCount(pResult.getTotalCount());
		} else {
			result.setPageNumber(0);
			result.setPageSize(0);
			result.setTotalCount(0);
		}
		result.setOperationResult(billboards);

		return result;
	}

}
